﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ZoneLineNew.Core.Extensions
{
    public static class DataTableExtensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            var list = new List<T>();

            // 获取目标类型的所有属性
            var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (DataRow row in table.Rows)
            {
                var obj = new T();

                foreach (var property in properties)
                {
                    // 确保该属性存在于 DataTable 的列中
                    if (table.Columns.Contains(property.Name))
                    {
                        // 如果列不为空，则赋值
                        if (row[property.Name] != DBNull.Value)
                        {
                            property.SetValue(obj, Convert.ChangeType(row[property.Name], property.PropertyType));
                        }
                    }
                }

                list.Add(obj);
            }
            return list;
        }
    }
}
